/**
 * 
 */
package ru.olympus.antonyhands.ao.client.widgets;

import java.util.List;

import ru.olympus.antonyhands.ao.client.AOHelperServiceAsync;
import ru.olympus.antonyhands.ao.shared.item.EItemParentType;
import ru.olympus.antonyhands.ao.shared.item.EItemsViewType;
import ru.olympus.antonyhands.ao.shared.util.StringPair;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * @author AntonyHands
 * @since 15.02.2012
 */
public class ItemsListBox extends BasicListBox {
	private BasicListBox _parentListBox;
	private EItemParentType _parentType;
	private EItemsViewType _viewType;

	public ItemsListBox(AOHelperServiceAsync service,
			BasicListBox parentListBox, EItemParentType parentType,
			EItemsViewType viewType) {
		this(service, parentListBox, parentType, viewType, null);
	}

	public ItemsListBox(AOHelperServiceAsync service,
			BasicListBox parentListBox, EItemParentType parentType,
			EItemsViewType viewType, String defaultValue) {
		super(service, defaultValue);
		_parentListBox = parentListBox;
		_parentType = parentType;
		_viewType = viewType;

		_parentListBox.addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent event) {
				refreshItemsList();
			}
		});
	}

	private void refreshItemsList() {
		getService().listItems(_parentType,
				_parentListBox.getCurrentValueCode(), _viewType,
				new AsyncCallback<List<StringPair>>() {
					@Override
					public void onSuccess(List<StringPair> result) {
						clear();
						for (StringPair pair : result)
							addItem(pair.getValue(), pair.getKey());
						updateCurrentValue();
					}

					@Override
					public void onFailure(Throwable caught) {
						clear();
						// TODO Auto-generated method stub
					}
				});
	}
}
